package com.atguigu.bigdata.spark.core.rdd.persist;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
/*

    RDD通过Cache或者Persist方法将前面的计算结果缓存，
    默认情况下会把数据以缓存在JVM的堆内存中。但是并不是这两个方法被调用时立即缓存，
    而是触发后面的action算子时，该RDD将会被缓存在计算节点的内存中，并供后面重用

    rdd中不会存储数据
    RDD对象可以重用，但是数据不行
 */

public class Spark03_RDD_Persist_JAVA {
    public static void main(String[] args) {
        // 1.创建配置对象
        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");

        // 2. 创建sparkContext
        JavaSparkContext sc = new JavaSparkContext(conf);

        JavaRDD<String> rdd = sc.parallelize(Arrays.asList("hello word", "hello spark", "hive","java"));

        JavaRDD<String> flatmap = rdd.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                String[] temp = s.split(" ");
                return Arrays.asList(temp).iterator();
            }
        });
        JavaPairRDD<String, Integer> pairMap = flatmap.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                System.out.println("@@@@@@@@@@@@@@@@");
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        //增加缓存
        pairMap.cache();

        JavaPairRDD<String, Integer> reduceByKey = pairMap.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });

        System.out.println(reduceByKey.collect().toString());

        System.out.println("-----------------------------------");

        JavaPairRDD<String, Iterable<Integer>> groupbyKey = pairMap.groupByKey();

        System.out.println(groupbyKey.collect().toString());

        sc.stop();

    }
}
